define(function( require, exports ){
	var $ = require('jquery');
	var util = require('util');
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var Menu = require('@base/common/menu');
	// 所有控件的设值都是{id: xxx, name: YYY}
	// 下拉输入框
	var DropText = view.container.extend({
		init: function( config ){
			config = pubjs.conf( config, {
				'width': 150,
				'height': 30,
				'placeholder': '',
				'def': '', // 默认选中的值
				'selfLoad': { // 在模块里拉取数据的情况<模块创建时已请求完数据>
					'url': '',
					'reqType': 'ajax',
					'method': 'get', // 或post
					'data': null,
					'param': null,
					'id': 'Id',
					'name': 'Name'
				},
				'toggle': false,
				'auto_send': false, // 选中后是否自动发消息
				'bindBlur': false, // 是否在文本框失去焦点时发消息
				'menu_config': null
			});
			this.$menuTemp = []; // selfLoad时存放自定义id的菜单数组
			this.Super( 'init', arguments );
		},
		afterBuild: function() {
			var self = this;
			var C = self.getConfig();
			self.$el = self.getDOM();
			self.$el.addClass('M-Select');
			$([
				'<div class="form-element-group">',
					'<input type="text" class="M-SelectInput form-element result" id=""/>',
					'<span class="M-SelectIcon form-element-extra arrow">',
						'<i class="triangle-top"/>',
					'</span>',
				'</div>'
			].join('')).appendTo( self.$el );
			// 缓存DOM
			self.$ipt = self.$el.find('.M-SelectInput');
			self.$ico = self.$el.find('.M-SelectIcon');
			// 设置输入框样式
			if(C.height){
				self.$ipt.css({
					'height': C.height,
					'line-height': (C.height - 15) + 'px'
				});
				self.$ico.css({
					'height': C.height,
					'line-height': (C.height - 15) + 'px'
				});
			}

			if(C.width){
				self.$el.width(C.width);
			}

			// 加属性
			if( C.placeholder ) {
				self.$ipt.attr( 'placeholder', C.placeholder );
			}
			// 默认值
			if( C.def ) {
				if( util.isString( C.def ) ) {
					self.$ipt.val( C.def );
				}
				else if( util.isObject( C.def ) ) {
					self.$ipt.val( C.def['name'] ).attr( 'id', C.def['id'] );
				}
			}
			// 模块自身拉取数据,再设到menu里面
			if( C.selfLoad['url'] ) {
				self.load();
			}
			// 点击整个组件时弹出菜单
			self.uiBind( self.$el, 'click', self.eventDropTextClick );
			// 输入keyup时搜索
			self.uiBind( self.$ipt, 'keyup', self.eventInputKeyup );
			if( C.bindBlur ) {
				self.uiBind( self.$ipt, 'blur', self.eventInputBlur );
			}
		},
		load: function() {
			var info = this.getConfig('selfLoad');
			pubjs.sync();
			switch (info.reqType){
				case 'ajax':
					if( info['method'] === 'get' ) {
						pubjs.data.get( info.url, info.param, this, 'onData' );
					}
					else if( info['method'] === 'post' ) {
						pubjs.data.post( info.url, info.data , info.param, this, 'onData' );
					}
				break;
				case 'websocket':
					pubjs.mc.send(info.url, info.param, this.onData.bind(this));
				break;
			}

		},
		onData: function( err, data ) {
			var info = this.getConfig('selfLoad');
			if( err ) {
				pubjs.error( err );
				pubjs.alert( err.message );
				return false;
			}
			if(data && data.items){
				for( var i = 0; i < data.items.length; i++ ) {
					this.$menuTemp.push({
						'id': data.items[i][info['id']] || i,
						'name': data.items[i][info['name']] || data.items[i]
					});
				}
			}
			pubjs.sync(true);
		},
		eventDropTextClick: function() {
			var self = this;
			var C = self.getConfig();
			var menu = this.get('menu');
			// 菜单配置
			var config = $.extend( false, {
				'trigger': this.$el,
				'relate_elm': this.$el,
				'data_set': [this.$dataSet],
				'offsetTop': -8,
				'options': this.$menuTemp
			}, C['menu_config'] );
			// 创建菜单
			if( !menu ) {
				self.create('menu', Menu.base, config);
			}
			else {
				// 是否需要菜单toggle
				if( C['toggle'] ) {
					menu.destroy();
				}
			}
			return false;
		},
		onMenuSelected: function( ev ) {
			var C = this.getConfig();
			var param = ev.param[0];
			// 缓存选中数据
			this.$dataSet = {
				'id': param['key'],
				'name': param['name']
			};
			// 将选中数据设到INPUT中
			this.setValue( this.$dataSet );
			this.get('menu').destroy();
			if( C.auto_send ) {
				this.fire( 'dropItemSelected', param );
			}
			return false;
		},
		// INPUT输入时进行菜单的搜索过滤
		eventInputKeyup: function() {
			var val = this.$ipt.val();
			var menu = this.get('menu');
			if( menu ) {
				// 全部退格掉时
				if( util.trim( val ) === '' ) {
					this.$dataSet = null;
				}
				menu.searching( val );
			}
		},
		// INPUT失去焦点时发消息
		eventInputBlur: function( evt, elm ) {
			var val = $(elm).val();
			this.setValue({
				'id': 0, // 新建的商家
				'name': val
			});
			this.fire( 'dropInputBlur', val );
			return false;
		},
		// 禁用下拉框选择和填写功能
		disable: function() {
			this.$ipt.attr('disabled', 'disabled');
			this.uiUnbind( this.$el, 'click' );
			return this;
		},
		// 起用下拉框选择和填写功能
		enable: function() {
			this.$ipt.removeAttr('disabled');
			this.uiBind( this.$el, 'click', this.eventDropTextClick );
			return this;
		},
		getData: function() {
			return this.$menuTemp;
		},
		setData: function( options ) {
			this.reset();
			this.$menuTemp = options;
		},
		/**
		 * [setValue 设置整个菜单的选项数据]
		 * @param {Mix} value [设值,可以是字符串,也可以是{id: 'xxx', name: '显示值'}的形式]
		 */
		setValue: function( value ) {
			if( util.isString( value ) ) {
				this.$ipt.val( value );
			}
			else if( util.isObject( value ) ) {
				this.$ipt.val( value['name'] ).attr('id', value['id']);
				this.$dataSet = value;
			}

		},
		getValue: function() {
			var val = this.$ipt.val();
			var id = this.$ipt.attr('id');
			if( this.$dataSet && val === this.$dataSet['name'] ) {
				id = this.$dataSet['id'];
			}
			return {
				'value': val,
				'id': id
			}
		},
		reset: function() {
			this.$ipt.val('').attr('id', "");
			this.$dataSet = null;
			this.enable();
		}
	});
	exports.text = DropText;

	// 下拉选框, 类似<select>标签
	var DropSelect = view.container.extend({
		init: function( config ){
			config = pubjs.conf( config, {
				'width': 150,
				'height': 30,
				'def': '',
				'toggle': true,
				'auto_send': false, // 选中选项后是否自动发消息
				'selfLoad': { // 在模块里拉取数据的情况<模块创建时已请求完数据>
					'url': '',
					'reqType': 'ajax',
					'method': 'get', // 或post
					'data': null,
					'param': null,
					'id': 'Id',
					'name': 'Name'
				},
				'menu_config': null
			});
			this.$menuTemp = []; // selfLoad时存放自定义id的菜单数组
			this.Super( 'init', arguments );
		},
		afterBuild: function() {
			var self = this;
			var C = self.getConfig();
			self.$el = self.getDOM();
			self.$el.addClass('M-SelectTag');
			$([
				'<div class="form-element-group">',
					'<span class="M-SelectTagCon form-element result" id=""/>',
					'<span class="M-SelectTagIcon form-element-extra arrow">',
						'<i class="triangle-top"/>',
					'</span>',
				'</div>'
			].join('')).appendTo( self.$el );
			// 缓存DOM
			var con = self.$con = self.$el.find('.M-SelectTagCon');
			self.$ico = self.$el.find('.M-SelectTagIcon');
			// 设置输入框样式
			if(C.height){
				con.css({
					'height': C.height,
					'line-height': (C.height - 15) + 'px'
				});
				self.$ico.css({
					'height': C.height,
					'line-height': (C.height - 15) + 'px'
				});
			}

			if(C.width){
				self.$el.width(C.width);
			}

			// 默认值
			if( C.def ) {
				if( util.isString( C.def ) ) {
					con.text( C.def );
				}
				else if( util.isObject( C.def ) ) {
					con.text( C.def['name'] ).attr( 'id', C.def['id'] );
					this.$dataSet = C.def;
				}
			}
			// 模块自身拉取数据,再设到menu里面
			if( C.selfLoad['url'] ) {
				self.load();
			}
			// 点击整个组件时弹出菜单
			self.uiBind( self.$el, 'click', self.eventDropClick );
		},
		load: function() {
			var info = this.getConfig('selfLoad');
			pubjs.sync();
			switch (info.reqType){
				case 'ajax':
					if( info['method'] === 'get' ) {
						pubjs.data.get( info.url, info.param, this, 'onData' );
					}
					else if( info['method'] === 'post' ) {
						pubjs.data.post( info.url, info.data , info.param, this, 'onData' );
					}
				break;
				case 'websocket':
					pubjs.mc.send(info.url, info.param, this.onData.bind(this));
				break;
			}
		},
		onData: function( err, data ) {
			var info = this.getConfig('selfLoad');
			pubjs.sync(true);
			if( err ) {
				pubjs.error( err );
				pubjs.alert( err.message );
				return false;
			}
			var i = 0, items = data.items;
			for( ; i < items.length; i++ ) {
				this.$menuTemp.push({
					'id': items[i][info['id']] || i,
					'name': items[i][info['name']] || data.items[i]
				});
			}
		},
		eventDropClick: function() {
			if(this.$disable) {
				return false;
			}
			var self = this;
			var C = self.getConfig();
			var menu = this.get('menu');
			// 菜单配置
			var config = $.extend( false, {
				'trigger': this.$el,
				'relate_elm': this.$el,
				'data_set': [this.$dataSet],
				'offsetTop': -8,
				'options': this.$menuTemp
			}, C['menu_config'] );
			// 创建菜单
			if( !menu ) {
				self.create('menu', Menu.base, config);
			}
			else {
				// 是否需要菜单toggle
				if( C['toggle'] ) {
					menu.destroy();
				}
			}
			return false;
		},
		onMenuSelected: function( ev ) {
			var C = this.getConfig();
			var param = ev.param[0];
			// 缓存选中数据
			this.$dataSet = {
				'id': param['key'],
				'name': param['name']
			};
			// 将选中数据设到INPUT中
			this.setValue( this.$dataSet );
			this.get('menu').destroy();
			if( C.auto_send ) {
				this.fire( 'dropItemSelected', param );
			}
		},
		/**
		 * [setValue 设置整个菜单的选项数据]
		 * @param {Mix} value [设值,可以是字符串,也可以是{id: 'xxx', name: '显示值'}的形式]
		 */
		setValue: function( value ) {
			if( util.isString( value ) ) {
				this.$con.text( value );
			}
			else if( util.isObject( value ) ) {
				this.$con.text( value['name'] ).attr('id', value['id']);
				this.$dataSet = value;
			}
			else {
				var menu_data = this.getConfig('menu_config/options');
				value = util.find(menu_data, value, 'id') || {};
			}

			this.$con.text( value['name'] ).attr('id', value['id']);
			this.$dataSet = value;
			return this;
		},
		disable: function() {
			this.$con.css({
				background: '#F5F5F5'
				,cursor: 'not-allowed'
			});

			this.$disable = true;
			return this;
		},
		enable: function() {
			this.$con.css({
				background: '#FFF'
				,cursor: 'pointer'
			});

			this.$disable = false;
			return this;
		},
		getValue: function() {
			return {
				'value': this.$con.text(),
				'id': this.$con.attr('id')
			}
		},
		reset: function() {
			var def = this.getConfig('def');
			if( def ) {
				this.$dataSet = def;
				this.$con.text( def['name'] ).attr('id', def['id']);
			}
			else {
				this.$con.text('').attr('id', "");
			}
		}
	});
	exports.select = DropSelect;

	// 下拉菜单按钮
	var DropButton = view.container.extend({
		init: function( config ){
			config = pubjs.conf( config, {
				'height': 30,
				'width': 150,
				'name': '', // 显示值
				'id': null, // 字段值
				'toggle': false,
				'auto_send': true, // 选中菜单后自动发消息
				'auto_set': true, // 选中菜单后自动将button设值
				'menu_config':  null
			});

			this.Super( 'init', arguments );
		},
		afterBuild: function() {
			var self = this;
			var C = self.getConfig();
			self.$el = self.getDOM();
			self.$el.addClass('M-SelectDrop');
			$([
				'<div class="form-element-group">',
					'<div class="M-SelectDropDom form-element result"/>',
					'<span class="M-SelectDropIcon form-element-extra arrow">',
						'<i class="triangle-top"/>',
					'</span>',
				'</div>'
			].join('')).appendTo( self.$el );
			self.$doms = self.$el.find('.M-SelectDropDom');
			// 设置默认值
			self.$doms.attr( 'id', C.id ).text( C.name );

			if(C.height){
				self.$doms.css({
					'height': C.height,
					'line-height': (C.height - 15) + 'px'
				});
				self.$el.find('.M-SelectDropIcon').css({
					'height': C.height,
					'line-height': (C.height - 15) + 'px'
				});
			}

			if(C.width){
				self.$el.width(C.width);
			}

			self.uiBind( self.$el, 'click', self.eventButtonClick );
		},
		eventButtonClick: function() {
			var self = this;
			var C = self.getConfig();
			var menu = this.get('menu');
			// 菜单配置
			var config = $.extend( false, {
				'trigger': this.$el,
				'relate_elm': this.$el
			}, C['menu_config'] );
			// 创建菜单
			if(self.$data && self.$data.length) {
				config.options = self.$data;
			}
			if( !menu ) {
				self.create('menu', Menu.base, config);
			}
			else {
				// 是否需要菜单toggle
				if( C['toggle'] ) {
					menu.destroy();
				}
			}
		},
		onMenuSelected: function( ev ) {
			var param = ev.param[0];
			var C = this.getConfig();
			// 缓存选中数据
			this.$dataSet = {
				'id': param['key'],
				'name': param['name']
			};
			if( C.auto_set ) {
				this.setValue( this.$dataSet );
			}
			if( C.auto_send ) {
				this.fire( 'dropItemSelected', param);
			}
			this.get('menu').destroy();
		},
		setValue: function( val ) {
			if(!util.isObject(val)) {
				var menu_data = this.getConfig('menu_config/options');
				val = util.find(menu_data, val, 'id') || {};
			}

			this.$doms
				.attr('id', val.id)
				.text( val.name );

			return this;
		},
		reset: function() {
			var c = this.getConfig();
			this.setValue({name: c.name, id: c.id});
			return this;
		},
		getValue: function(key) {
			var ret = {
				'id': this.$doms.attr('id')
				,'name': this.$doms.text()
			}

			return key ? ret.id : ret;
		},
		setData: function(data) {
			this.$data = data;
			return this;
		}
	});
	exports.button = DropButton;

});